package com.pdwl.cashoutpay.controller;

import com.pdwl.cashoutpay.entity.Trade;
import com.pdwl.cashoutpay.entity.res.BaseEntity;
import com.pdwl.cashoutpay.entity.res.TradeRes;
import com.pdwl.cashoutpay.service.OrderService;
import com.pdwl.cashoutpay.util.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 交易确认接口
 */
@Controller
@RequestMapping("mailCheck")
public class MailCheck {

    @Value("${mailCheckUrl}")
    private String mailCheckUrl;

    @Value("${publicKey}")
    private String publicKey;

    @Value("${costMailNotifyUrl}")
    private String costMailNotifyUrl;


    @Autowired
    OrderService orderService;

    @RequestMapping("check")
    public void check(HttpServletRequest request, HttpServletResponse response) throws Exception {
        LogUtils.logInfo("交易开始，发送短信验证码");
        response.setHeader("Content-type", "textml;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        JSONObject map = JsonUtil.getJson(request);

        BaseEntity baseEntity = new BaseEntity();
        if (map.getString("sign").equals(Sign.getSign(map))) {
            Trade order = orderService.findByOurOrderId(map.getString("ourOrderId"));

            baseEntity = mailCheck(order, map.getString("smsCode"));
        } else {
            LogUtils.logInfo("验签失败！");
            baseEntity.setError_code("20005");
            baseEntity.setError_message("验签失败，请重新验签！");
        }

        JSONObject json = JSONObject.fromObject(baseEntity);//将java对象转换为json对象
        String res = json.toString();
        response.getWriter().write(res);
    }

    /**
     * 请求上游，短信消费
     *
     * @param trade
     * @return
     * @throws Exception
     */
    public BaseEntity mailCheck(Trade trade, String smsCode) throws Exception {
        BaseEntity baseEntity = new BaseEntity();
        Map payReq = new HashMap<String, String>();
        payReq.put("orderNo", trade.getOurorderid()); //商户订单号
        payReq.put("subMerchCode", trade.getSubmerchcode()); //子商户号
        payReq.put("amount", trade.getAmount()); //交易金额
        payReq.put("notifyUrl", costMailNotifyUrl); //回调地址
        payReq.put("smsCode", smsCode); //短信验证码
        String cvv = RSAUtils.encryptByPublicKey(trade.getCvv().getBytes(), publicKey);
        payReq.put("cvv", cvv);
        payReq.put("expireDate", trade.getExpiredate()); //有效期
        payReq.put("channelCode", "fastSoopay"); //通道编号
        payReq.put("criditNo", trade.getCriditno()); //交易卡号
        payReq.put("bankPhoneNo", trade.getBankphoneno()); //银行预留手机号

        LogUtils.logInfo("确定交易，发送短信验证码，发送数据：" + payReq.toString());

        String res = HttpUtil.formUpload(mailCheckUrl, payReq);
        LogUtils.logInfo("确定交易，发送短信验证码，返回数据：" + res.toString());

        org.json.JSONObject jsonRes = new org.json.JSONObject(res);
        String flag = (String) jsonRes.getString("flag");
        String error_message = (String) jsonRes.getString("errorMessage");
        if ("true".equals(flag)) {
            TradeRes tradeRes = new TradeRes();
            tradeRes.setOrderid(trade.getOrderid());
            tradeRes.setOurorderid(trade.getOurorderid());
            tradeRes.setAmount(trade.getAmount());
            tradeRes.setNotifyurl(trade.getNotifyurl());
            tradeRes.setCriditno(trade.getCriditno());
            tradeRes.setBankphoneno(trade.getBankphoneno());
            tradeRes.setStatus(trade.getStatus());
            tradeRes.setMessage(trade.getMessage());

            baseEntity.setError_code("1");
            baseEntity.setError_message(error_message);
            baseEntity.setData(tradeRes);
        } else {
            baseEntity.setError_code("2");
            baseEntity.setError_message(error_message);
        }
        return baseEntity;
    }
}
